from flask import render_template, request
from flask_login import current_user

from . import main
from ..models import Posts
from .. import db

@main.route('/index/', methods=['GET', 'POST'])
@main.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        comment = request.form.get('comment')
        if comment and current_user.is_authenticated():
            new_post = Posts()
            new_post.user_id = current_user.id
            new_post.body = comment

            query = Posts.query.order_by(Posts.id.desc())
            count = query.count()
            new_post.id = count
            if count > 0:
                prv_post = query.first()
                new_post.gift_id = count - 1
            else:
                prv_post = new_post
                new_post.gift_id = 0
            db.session.add(new_post)
            db.session.commit()
        return render_template('index-posted.html', new_post=new_post,
                               gift_post=prv_post)
    return render_template('index.html')
